/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package database;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import rentaldb.Lease;
import rentaldb.Service;

/**
 *
 * @author Pop
 */
public class ServiceDao {
    private EntityManager em;
    private EntityManagerFactory emf;
    
    public ServiceDao(){
        try{
            emf = Persistence.createEntityManagerFactory("RentaldbPU");
            em = emf.createEntityManager();  
        }catch(Exception e){ System.out.println(e);}
    }
    
    public void persist(Service s){
        em.getTransaction().begin();
        em.persist(s);
        em.getTransaction().commit();
        
    }
    
    public void update(Service s){
        em.getTransaction().begin();
        em.merge(s);
        em.getTransaction().commit();
    }
    
    public void delete(Service s) throws Exception{
        s = getServiceById(s.getServiceId());
        em.getTransaction().begin();
        em.remove(s);
        em.getTransaction().commit();
    }
    
    public Service getServiceById(Integer id) throws Exception{
        //em.createQuery("select * from property");
        Query q = em.createNamedQuery("Service.findByServiceId");
        q.setParameter("serviceId", id);
        Service s = (Service)q.getSingleResult();
        
        return s;
    }
    
    public List<Service> getAllServices() throws Exception{
        Query q = em.createNamedQuery("Service.findAll");
        List<Service> serviceList = q.getResultList();
        
        return serviceList;
    }
}

